<?php

namespace App\Http\Resources;

use App\Http\Responses\Resource;

class Book extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {

        $flowers_count = $this->rewarded()->where('gift_id',1)->count();
        $rewarded_count = $this->rewarded()->where('gift_id','>',1)->count();

        return [

            'id' => $this->id,
            'name' => $this->name,
            'cover' => $this->cover,
            'book_num' => $this->book_num,
            'status' => $this->status,
            'introduction' => $this->introduction,
            'author' => $this->author,
            'labels' => json_decode($this->labels,true),
            'status' => $this->status,
            'last_chapter' => $this->getLastChapter($this),
            'read_count' => $this->read_counts,
            'collection_counts' => $this->collection_counts,
            'book_type' =>  $this->bookType ? $this->bookType->name : null,
            'comments_count' => $this->comments()->count(),
            'flowers_count' => $flowers_count,
            'rewarded_count' => $rewarded_count,
            'words' => $this->words,
            'last_modify_time' => $this->last_modify_time

        ];

    }


    protected function getLastChapter(Book $book){

        $chapter = $book->chapters()
            ->where('status',1)
            ->orderBy('id','desc')
            ->first();

        if (empty($chapter)){
            return null;
        }

        return new Chapter($chapter);
    }

}
